<template>
  <div class="user-manage">
    <!-- 工具栏：搜索和新增用户按钮 -->
    <el-card>
      <div class="toolbar">
        <el-input
            v-model="searchQuery"
            placeholder="搜索用户名、姓名或邮箱"
            clearable
            style="width: 300px;"
            @keyup.enter.native="handleSearch"
        />
        <el-button type="primary" icon="el-icon-plus" @click="openAddDialog">
          新增用户
        </el-button>
      </div>

      <!-- 用户列表表格 -->
      <el-table :data="filteredUsers" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="full_name" label="姓名" />
        <el-table-column prop="role" label="角色" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form :model="currentUser" ref="userForm" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="currentUser.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="姓名" prop="full_name">
          <el-input v-model="currentUser.full_name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="currentUser.role" placeholder="请选择角色">
            <el-option label="用户" value="用户" />
            <el-option label="管理员" value="管理员" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="currentUser.email" autocomplete="off" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="currentUser.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="是否订阅" prop="subscribed">
          <el-switch v-model="currentUser.subscribed" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import { getUsersFuzzy, createUser, updateUser, deleteUser } from '../api/user'

// 搜索关键词
const searchQuery = ref('')

// 用户列表数据
const users = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增用户')
const currentUser = ref({
  id: null,
  username: '',
  full_name: '',
  role: '用户',
  email: '',
  phone: '',
  subscribed: false
})

// 获取用户列表
const fetchUsers = async () => {
  try {
    const res = await getUsersFuzzy(searchQuery.value)
    users.value = res.users
  } catch (err) {
    console.error('获取用户数据失败', err)
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchUsers()
})

// 计算属性实现模糊查询
const filteredUsers = computed(() => {
  if (!searchQuery.value) return users.value
  const query = searchQuery.value.trim().toLowerCase()
  return users.value.filter(user =>
      user.username.toLowerCase().includes(query) ||
      user.full_name.toLowerCase().includes(query) ||
      user.email.toLowerCase().includes(query)
  )
})

// 搜索触发
const handleSearch = () => {
  fetchUsers()
}

// 打开新增对话框
const openAddDialog = () => {
  dialogTitle.value = '新增用户'
  currentUser.value = {
    id: null,
    username: '',
    full_name: '',
    role: '用户',
    email: '',
    phone: '',
    subscribed: false
  }
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = (user) => {
  dialogTitle.value = '编辑用户'
  currentUser.value = {...user}
  dialogVisible.value = true
}

// 保存新增或编辑的用户
const handleSave = async () => {
  try {
    if (currentUser.value.id) {
      // 编辑更新
      await updateUser(currentUser.value.id, currentUser.value)
      const index = users.value.findIndex(u => u.id === currentUser.value.id)
      if (index !== -1) {
        users.value[index] = {...currentUser.value}
      }
      ElMessage.success('更新成功')
    } else {
      // 新增用户
      const res = await createUser(currentUser.value)
      users.value.push(res.user)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
  } catch (err) {
    console.error('保存失败', err)
    ElMessage.error('保存失败')
  }
}

// 删除用户
const handleDelete = (user) => {
  ElMessageBox.confirm(`确认删除用户 ${user.username} 吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteUser(user.id)
      users.value = users.value.filter(u => u.id !== user.id)
      ElMessage.success('删除成功')
    } catch (err) {
      console.error('删除失败', err)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
  })
}
</script>

<style scoped>
.user-manage {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
